package com.umfwechat.h5.controller.advanceSettle;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.ConfigConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.common.prop.UmfPropModel;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.SmsCheckUtil;
import com.umfwechat.util.StringUtil;
import com.umpay.operation.model.edrawInf.EdrawInf;
import com.umpay.operation.model.product.MerProduct;
import com.umpay.operation.service.colInfo.remote.ColInfoRemote;
import com.umpay.operation.service.edrawInf.remote.EdrawInfServiceRemote;
import com.umpay.operation.service.product.MerProductServiceRemote;
import com.umpay.pm20.po.BatchPayConf;
import com.umpay.pm20.po.BatchPayMU;
import com.umpay.pm20.service.BatchPayConfRemote;
import com.umpay.pm20.service.ProductInfRemote;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.AppChannel;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.AppChannelServiceRemote;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.xml.XmlData;
import com.umfwechat.util.HttpUtil;

/**
 * @desc  收入结算开通功能模块
 * @author Wangzhilong
 * @date 2017-5-11 下午7:41:12
 */
@Controller
@RequestMapping("/h5/advanceSettle")
public class AdvanceSettleController {

    private static Logger logger = LoggerFactory.getLogger(AdvanceSettleController.class);
    
    //查询商户产品关系
  	@Resource
  	private MerProductServiceRemote merProductServiceRemote;
	//查询渠道信息接口
	@Resource
	private AppChannelServiceRemote appChannelServiceRemote; 
	//查询店铺信息接口
	@Resource
	private StoreInfServiceRemote storeInfServiceRemot;
	// 查询银行账户信息的接口
	@Resource
	private EdrawInfServiceRemote edrawInfRemote;
	//添加付款用途
	@Autowired
	private BatchPayConfRemote batchPayConfRemote;
	//添加商户对账信息
	@Resource
	private ColInfoRemote colInfoRemote;
		
	
	/**
	 * 提前结算开通页面初始化
	 * @param session
	 * @param request
	 * @param merId
	 * @return
	 */
	@RequestMapping(value = "/initialize",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String Initialize(HttpServletRequest request,String merId){		
		logger.info("【进入提前结算开通页面初始化】");
		Map<String, Object> result = new HashMap<String, Object>();
		
		// 从session中获取主商户号
		if (request.getSession().getAttribute(CommonConsts.MERID) != null) {
			merId = StringUtil.trim(request.getSession().getAttribute(CommonConsts.MERID).toString());
		}
		logger.info("【从session中获取用户的merId】=" + merId);
		// 判断openid
		if (StringUtil.isEmpty(merId)) {
			logger.info("【获取merId获取失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433044);
		}

		// 调用查询绑定银行卡信息接口
		logger.info("【调用查询商户绑定银行卡接口】merId：" + merId);
		com.umpay.operation.common.ReqMessage req = ReqMessageUtil.makeOpReq();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put(CommonConsts.MERID, merId);
		reqMap.put(CommonConsts.DELAYDAYS, ValueConsts.EDRAW_DELAYDAYS);
		reqMap.put(CommonConsts.STATE, ValueConsts.EDRAW_STATE);
		reqMap.put(CommonConsts.RECVBANKACCPRO,ValueConsts.EDRAW_RECVBANKACCPRO);
		req.setReqMap(reqMap);
		com.umpay.operation.common.ResMessage res = null;
		try {
			logger.info("【查询商户绑定银行卡信息接口】输入参数：ReqMessage=" + req);
			res = edrawInfRemote.queryEdrewInf(req);
			logger.info("【查询商户绑定银行卡信息接口】输出参数：ResMessage" + res);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("【查询商户绑定银行卡信息接口异常】"), e);
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433079);
		}

		if (!RetCode.SUCCESS.equals(res.getRetCode())) { // 查询失败
			logger.info("【调用查询商户绑卡信息接口失败!】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433058);
		}
		EdrawInf edrawInfReData = (EdrawInf) res.getResMap().get(
				CommonConsts.EDRAWINF);
		if (edrawInfReData == null) { // 查询无数据
			logger.info("【调用查询商户绑卡信息接口无数据】merId：" + merId);
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433080);
		}
        //获取银行卡号
		String bankAccount = StringUtil.trim(edrawInfReData.getBankAccount());
		//截取银行卡号后四位
		String substring = bankAccount.substring(bankAccount.length()-4, bankAccount.length());
		
		// 店铺部署详情接口
		ReqMessage reqMe = ReqMessageUtil.makeSpReq();
		reqMe.getReqMap().put(CommonConsts.STOREID, merId);
		ResMessage resMe = null;
		try {
			logger.info("【店铺部署详情接口】输入参数 ：ReqMessage=" + reqMe);
			resMe = storeInfServiceRemot.getStoreInfByPri(reqMe);
			logger.info("【店铺部署详情接口】输出参数:ResMessage=" + resMe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("【店铺部署详情接口异常】"), e);
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}

		// 获取店铺详情失败
		if (!RetCode.SUCCESS.equals(resMe.getRetCode())) {
			logger.info("【店铺部署详情接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}
		// 获取店铺简称信息
		StoreInf storeInf = (StoreInf) resMe.getResMap().get(CommonConsts.STOREINF);
		String payeeMobileId = storeInf.getPayeeMobileId();
		
		//request.getSession().setAttribute(CommonConsts.PAYEEMOBILEID, payeeMobileId);
	    payeeMobileId= payeeMobileId.replaceAll("(\\d{3})\\d{4}(\\w{4})","$1******$2");//脱敏
		
		//信息传到前台
		result.put(CommonConsts.MERID,merId);
		//银行卡名称
		result.put(CommonConsts.EDRAW_BANKNAME,StringUtil.trim(edrawInfReData.getBankName()));
		//银行卡号
		result.put(CommonConsts.BANKACCOUNT,substring);
		//result.put(CommonConsts.BINBANKID, StringUtil.trim(edrawInfReData.getBinBankId()));
		//result.put(CommonConsts.COLACCNAME, StringUtil.trim(edrawInfReData.getColAccName()));
		result.put(CommonConsts.STATE, StringUtil.trim(edrawInfReData.getState()));
		//产品名称
		result.put(CommonConsts.PRODUCTNAME,UmfPropModel.INSTANCE.getPropValue(ConfigConsts.MAINPRODUCTNAME_ADVANCESETTLE));
		//手机号
		result.put(CommonConsts.BANKMOBILEID,payeeMobileId);
		logger.info("【结束提前结算开通页面初始化】");
		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE,result);
	}
	
	
	
	/**
	 * 提前结算开通
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/dredge",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String dredge(String merId,String bankMobileId,String verifyCode,HttpServletRequest request, HttpServletResponse response){		
		logger.info("【进入提前结算开通】");
		HttpSession session=request.getSession();
		
		logger.info("【调用校验验证码信息接口，校验短信验证码】====开始！===");
		
		// 店铺部署详情接口
		ReqMessage reqMe = ReqMessageUtil.makeSpReq();
		reqMe.getReqMap().put(CommonConsts.STOREID, merId);
		ResMessage resMe = null;
		try {
			logger.info("【店铺部署详情接口】输入参数 ：ReqMessage=" + reqMe);
			resMe = storeInfServiceRemot.getStoreInfByPri(reqMe);
			logger.info("【店铺部署详情接口】输出参数:ResMessage=" + resMe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(String.format("【店铺部署详情接口异常】"), e);
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}

		// 获取店铺详情失败
		if (!RetCode.SUCCESS.equals(resMe.getRetCode())) {
			logger.info("【店铺部署详情接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433091);
		}
		// 获取店铺简称信息
		StoreInf storeInf = (StoreInf) resMe.getResMap().get(CommonConsts.STOREINF);
		bankMobileId = storeInf.getPayeeMobileId();
		
		if(StringUtil.isEmpty(bankMobileId)){
			logger.info("【获取手机号失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433061);
		}
		if(StringUtil.isEmpty(verifyCode)){
			logger.info("【获取验证码失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433064);
		}
		
		String smsVerifyTrace=StringUtil.trim(session.getAttribute(CommonConsts.SMSVERIFYTRACE));	//从session中获取流水号
		if(StringUtil.isEmpty(smsVerifyTrace)){
			logger.info("【获取流水号失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433062);
		}
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~检验短信验证码接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		Map<String,String> res=SmsCheckUtil.checksms(bankMobileId, smsVerifyTrace, verifyCode);
		if(res.isEmpty()||res==null){
			logger.info("【校验验证码失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433078);
		}
		if(!RetCode.SUCCESS.equals(res.get(CommonConsts.RETCODE))){		//验证码错误
			logger.info("【校验验证码失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433078);
		}
		logger.info("【调用校验验证码信息接口，校验短信验证码】======结束！====+++++++");
		
		logger.info("【从session中获取用户的merId】=" + merId);
		// 判断openid
		if (StringUtil.isEmpty(merId)) {
			logger.info("【获取merId获取失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433044);
		}
		
		// 收入结算产品编号
		String productId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_ADVANCESETTLE);
		if (StringUtil.isEmpty(productId)) {
			logger.info("【获取收入结算产品编号失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		// 收入结算主产品编号
		String mainProductId =  UmfPropModel.INSTANCE.getPropValue(ConfigConsts.MAINPRODUCTID_ADVANCESETTLE);
		if (StringUtil.isEmpty(mainProductId)) {
			logger.info("【获取收入结算主产品编号失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		
		// 渠道开通列表返回查询接口
		ReqMessage reqM = ReqMessageUtil.makeSpReq();
		reqM.getReqMap().put(CommonConsts.APPSYSID,merId);
		reqM.getReqMap().put(CommonConsts.PRODUCTID,productId);
		ResMessage resM=null;
		try{
			logger.info("【根据主键查询渠道表接口】输入参数：ReqMessage = " + reqM);
			resM =appChannelServiceRemote.queryByAppSysId(reqM);
			logger.info("【根据主键查询渠道表接口】输出参数：ResMessage =  " + resM);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【根据主键查询渠道表接口异常】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433093);
		}
		if (!RetCode.SUCCESS.equals(resM.getRetCode())
				&& !RetCode.MER_NOT_EXIST.equals(resM.getRetCode())) {
			logger.info("【根据主键查询渠道表接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433002);
		}
		
		if(RetCode.SUCCESS.equals(resM.getRetCode())){
			// 获取查询到的渠道信息
			AppChannel appChannel = (AppChannel) resM.getValue(CommonConsts.APPCHANNEL);
			if (appChannel.getState().equals(3)) {
				logger.info("【该商户的提前结算已经开通】");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433111);
			}
		}

		logger.info("[saas平台]-开始开通提前结算各种配置-----start.");
		Map<String, String> merJoin = registerMerJoin(merId,storeInf.getPayeeName());
		if (!RetCode.SUCCESS.equals(merJoin.get(CommonConsts.RETCODE))) {
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433093);
		}
		logger.info("[saas平台]-结束开通提前结算各种配置-----end.");

		
		//开通渠道
		ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		reqMess.getReqMap().put(CommonConsts.APPSYSID, merId);
		reqMess.getReqMap().put(CommonConsts.MAINPRODUCTID, mainProductId);
		reqMess.getReqMap().put(CommonConsts.STATE,ValueConsts.APP_CHANNEL_STATE_THREE);
		reqMess.getReqMap().put(CommonConsts.PRODUCTID, productId);
		ResMessage resMess=null;
		if (RetCode.MER_NOT_EXIST.equals(resM.getRetCode())) {
			reqMess.put(CommonConsts.APPNAME,UmfPropModel.INSTANCE.getPropValue(ConfigConsts.MAINPRODUCTNAME_ADVANCESETTLE));
			try {
				logger.info("【通过主键插入渠道表】输入参数：ReqMessage="+reqMess.toString());
				resMess=appChannelServiceRemote.insertChannel(reqMess);
				logger.info("【通过主键插入渠道表】输出参数：ResMessage="+resMess);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("【通过主键插入渠道表异常】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433093);
			}
			//判断返回码是否是0000
			if(!RetCode.SUCCESS.equals(resMess.getRetCode())&&!RetCode.DATA_EXISTS.equals(resMess.getRetCode())){	
				logger.info("【通过主键插入渠道表失败】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,
						MsgConsts.E00433093);
			}else{
				logger.info("【通过主键插入渠道表成功】");
				return ResultJsonUtil.resultJson(RetCode.SUCCESS,MsgConsts.I00433104);
			}
		} else {
			try {
				// 审核通过更新接口
				logger.info("【审核通过更新接口】输入参数：ReqMessage=" + reqMess);
				resMess = appChannelServiceRemote.updateChannel(reqMess);
				logger.info("【审核通过更新接口】输出参数：ReqMessage=" + resMess);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("【审核通过更新接口异常】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433093);
			}
			if (!RetCode.SUCCESS.equals(resMess.getRetCode())) {
				logger.info("【审核通过更新失败】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433093);
			} else {
				logger.info("【审核通过更新成功】");
				return ResultJsonUtil.resultJson(RetCode.SUCCESS,MsgConsts.I00433104);
			}

		}

	}
	
	
	/**
	 * 开通商户提前结算，步骤：【5】：添加商户对账信息【6】：添加主商户产品关系 【7】：配置产品费率信息
	 * @param appInfo
	 */
	//@RequestMapping(value = "/registerMerJoin",produces="application/json;charset=UTF-8")
	//@ResponseBody
	public Map<String,String> registerMerJoin(String merId,String payeeName){
		Map<String,String> map = new HashMap<String,String>();
		String productId = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PRODUCTID_ADVANCESETTLE);
		logger.info("==★========★==主商户注册操作，开始执行==★========★==");
		String[] productIds = productId.split(CommonConsts.AND);
		try {
			//对账模板 
			String merProCcolids = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.MerPro_ORT_COLID);
		    String[] colids = merProCcolids.split(CommonConsts.COMMA);
			logger.info("==★====★★★开始★★★★====★==主商户注册操作【5】：添加商户对账信息");
			for (String colid : colids) {
			  Map<String,String> mapp= addMerRecon(merId,colid);
		      if(!RetCode.SUCCESS.equals(mapp.get(CommonConsts.RETCODE))){
			    map.put(CommonConsts.RETCODE,RetCode.FAIL);
			    return map;
			  }
			}
			logger.info(String.format("==★====★★★★结束★★★====★==主商户注册操作【5】：添加商户对账信息"));
			
			
			
			logger.info("==★====★★★开始★★★★====★==主商户注册操作【6】：添加主商户产品关系");
			for (String productID : productIds) {
				logger.info("==★====★★★★★★★★★★★====★==主商户注册操作【6】：添加主商户产品关系信息，产品编号：productID="+productID);
				Map<String,String> mapp= addMerProduct(merId,productID);
				if(!RetCode.SUCCESS.equals(mapp.get(CommonConsts.RETCODE))){
					map.put(CommonConsts.RETCODE,RetCode.FAIL);
					return map;
				}
			}
			logger.info(String.format("==★====★★★★结束★★★====★==主商户注册操作【6】：添加主商户产品关系"));
		   
		    logger.info("==★====★★★★★开始★★★★★★====★==主商户注册操作【7】：产品费率信息，产品编号："+productIds);
		    // 开通费率
			for (String productID : productIds) {
				logger.info(String.format("==★====★★★★★★★★★★★====★==主商户注册操作【7】：产品费率信息，产品编号：productID"+productID));
			    Map<String, String> mapp = allocationRate(productID,merId);
				if(!RetCode.SUCCESS.equals(mapp.get(CommonConsts.RETCODE))){
					map.put(CommonConsts.RETCODE,RetCode.FAIL);
					return map;
				}
			}
			logger.info(String.format("==★====★★★★★结束★★★★★★====★==主商户注册操作【7】：产品费率信息，产品编号："+productIds));

			
			//添加付款用途
			logger.info(String.format("==★====★★★★★★★★★★★====★==主商户注册操作【8】：添加付款用途，主商户：merId"+merId));
					
		    Map<String, String> mapppp = configureBatchPay(merId,payeeName);
				if(!RetCode.SUCCESS.equals(mapppp.get(CommonConsts.RETCODE))){
					map.put(CommonConsts.RETCODE,RetCode.FAIL);
					return map;
				}
			logger.info(String.format("==★====★★★★★结束★★★★★★====★==主商户注册操作【8】：添加付款用途，主商户：merId"+merId));

			
			map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
			logger.info(String.format("==★========★==主商户注册操作，结束执行==★========★=="));
			return map;
		} catch (Exception e) {
			logger.error(String.format("==★====★★★★★★★★====★==主商户注册操作：操作失败"),e);
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
	}
	
	/**
	 * 主商户注册操作【5】：添加主商户对账信息
	 */
	public Map<String,String> addMerRecon(String merId,String colid){
		
		Map<String,String> map = new HashMap<String,String>();
		com.umpay.operation.common.ReqMessage reqQuery = ReqMessageUtil.makeOpReq();
		com.umpay.operation.common.ResMessage res = null;
		reqQuery.put(CommonConsts.COLID,colid);	//对账版本
		reqQuery.put(CommonConsts.MERID,merId);
		reqQuery.put(CommonConsts.CURRENT_PAGE,ValueConsts.PAGE_ONE);
		reqQuery.put(CommonConsts.PAGE_SIZE,"100");
		try {
			// 查询商户对账信息
			res = colInfoRemote.pageQuerMerCol(reqQuery);
		} catch (Exception e) {
			logger.error("==★====★★★★★★====★==主商户注册操作【5】：添加主商户对账信息异常");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		if(!RetCode.SUCCESS.equals(res.getRetCode())){
			logger.info("==★====★====★==主商户注册操作【5】：添加主商户对账信息执行失败");
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		Integer totalSize = (Integer) res.getResMap().get(CommonConsts.TOTAL_SIZE);
		if(totalSize == 0){
			// 添加商户对帐信息
			com.umpay.operation.common.ReqMessage reqAdd = ReqMessageUtil.makeOpReq();
			reqAdd.put(CommonConsts.COLID,colid);
			reqAdd.put(CommonConsts.MERID,merId);
			reqAdd.put(CommonConsts.STATUS,ValueConsts.STATE_ONE);
			reqAdd.put(CommonConsts.MOD_USER,CommonConsts.SAAS);
			try {
				res = colInfoRemote.addMerCol(reqAdd);
			} catch (Exception e) {
				logger.error("==★====★★★★★★====★==主商户注册操作【5】：添加主商户对账信息异常");
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				return map;
			}
			if(!RetCode.SUCCESS.equals(res.getRetCode())){
				logger.info("==★====★====★==主商户注册操作【5】：添加主商户对账信息失败");
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				return map;
			}
		}
		map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
		return map;
	}
	
	/**
	 * 主商户注册操作【6】：添加主商户产品关系
	 */
	public Map<String,String> addMerProduct(String merId,String productId) throws Exception {
		logger.info("==★====主商户注册操作【6】：添加主商户产品关系==★====初始化产品参数====读取配置产品信息!");
		// 组装所有需要参数，读取配置产品信息
		Map<String,String> map = new HashMap<String,String>();
		
		com.umpay.operation.common.ReqMessage reqM = ReqMessageUtil.makeOpReq();
		com.umpay.operation.common.ResMessage resM = null;
		reqM.put(CommonConsts.MERID,merId);	//商户ID
		reqM.put(CommonConsts.PRODUCTID,productId);	//产品ID
		try {
			logger.info("==★====主商户注册操作【6】：通过商户ID和产品ID，查看商户产品的绑定关系==★====开始==ReqMessage=="+reqM);
			resM = merProductServiceRemote.getMerProductByKey(reqM);
			logger.info("==★====主商户注册操作【6】：通过商户ID和产品ID，查看商户产品的绑定关系==★=====结束==ResMessage="+resM);
			
		} catch (Exception e) {
			logger.error(String.format("==★====★★★★★★====★==主商户注册操作【6】：查询主商户产品关系异常"),e);
		}
		if(!RetCode.SUCCESS.equals(resM.getRetCode())){
			logger.info("==★====★★★★★★====★==主商户注册操作【6】：查询商户产品的绑定关系失败，返回错误信息：" + resM);
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		//获取查到的商户产品
		MerProduct merProduct = (MerProduct) resM.getResMap().get(CommonConsts.MERPRODUCT);
		logger.info("商户产品:"+merProduct);
		if(null==merProduct||CommonConsts.SPACE.equals(merProduct)){
			//调用CRM进行创建关系
			Map<String, Object> reqMap = new HashMap<String, Object>();
			String payElement = CommonConsts.SPACE;// 支付元素
			String ptype = productId.substring(3, 4); // 取产品号中付款标志位
			if (ptype.equals("5") || ptype.equals("7")) { // 信用卡无磁无密支付，信用卡无磁无密预授权
				payElement = "010203"; // 设置支付要素（cvv）
			} else if (ptype.equals("6")) { // 借记卡无磁无密支付
				payElement = "01";
			} else if (ptype.equals("4")) { // U付账户支付
				payElement = CommonConsts.SPACE;
			} else if ("P0000001".equals(productId) || "P0000002".equals(productId)) {
				payElement = CommonConsts.SPACE;
			} else {
				payElement = CommonConsts.SPACE;
			}
			reqMap.put(CommonConsts.RPID, reqM.getRpid());
			reqMap.put(CommonConsts.FUNCODE,"QYZH");	
			reqMap.put(CommonConsts.MERID,merId);	//商户ID
			reqMap.put(CommonConsts.ACCTYPETAG, "2");	//开户类型
			reqMap.put(CommonConsts.PRODUCTID, productId);	//产品ID
			reqMap.put(CommonConsts.PLAYELEMENTS, payElement);
			reqMap.put(CommonConsts.REGPOINTTAG, "40");	//开通渠道
			reqMap.put(CommonConsts.SENDSMS, "2");
			Map<String, Object> crmResult = null;
			String retCode = CommonConsts.SPACE;
			try {
				XStream xstream = new XStream(new DomDriver());
				// URL配置文件取
				String url = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.UPAY_CRM_ACCOUNT_URL);	//获取商户产品绑定关系URL
				logger.info("==★====主商户注册操作【6】：添加主商户产品关系==★开始====开始添加商户产品关系");
				//调用受理注销用户标识接口
				crmResult = (Map<String, Object>)HttpUtil.getResObjPost(url, xstream, reqMap);
				logger.info("==★====主商户注册操作【6】：添加主商户产品关系==★结束====开始添加商户产品关系crmResult"+crmResult);
				if(crmResult==null || crmResult.isEmpty()) {
					logger.info("==★====★★★★★★====★==主商户注册操作【6】：请求CRM系统失败:添加商户产品的绑定关系失败");
					map.put(CommonConsts.RETCODE,RetCode.FAIL);
					return map;
				}
				retCode = (String) crmResult.get(CommonConsts.RETCODE);
				if (!RetCode.SUCCESS.equals(retCode)){
					logger.info(String.format("==★====★★★★★★★====★==主商户注册操作【6】：请求CRM系统失败:添加商户产品的绑定关系失败"));
					map.put(CommonConsts.RETCODE,RetCode.FAIL);
					return map;
				}
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
				return map;
			} catch (Exception e) {
				logger.info("==★====★★★★★★====★==主商户注册操作【6】：请求CRM系统失败:添加商户产品的绑定关系失败  "+e);
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				return map;
			}
		}
		map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
		return map;
	}
	
	/**
	 * 主商户注册操作【7】： 配置费率
	 */
	public Map<String,String> allocationRate(String productID,String merId){

		logger.info("【7】：添加产品费率信息，产品编号：" + productID);
		Map<String,String> map = new HashMap<String, String>();
		
		ReqMessage re = ReqMessageUtil.makeSpReq();
		String rpid = re.getRpid();
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(CommonConsts.RPID, rpid);
		params.put(CommonConsts.REQDATE, re.getReqDate());
		params.put(CommonConsts.REQTIME, re.getReqTime());
		params.put(CommonConsts.MERID,merId);
		params.put(CommonConsts.START_DATE, re.getReqDate());// 起始日期
		
		String url=null;
		if(ValueConsts.PRODUCTID_ES_PAYMENT_CODE.equals(productID)){
			url =UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PAYMENT_ACC_FEE_URL);
			//1&5000&11&0&0.012&0&spapply
			String rateDate =UmfPropModel.INSTANCE.getPropValue(ConfigConsts.PAYMENT_ACC_FEE_DATE);
			String[] split = rateDate.split(CommonConsts.AND);
			// 配置公共参数
			params.put(CommonConsts.PRODUCTID, productID);// 产品号
			params.put(CommonConsts.MINFEE,split[0]);//保底手续费
			params.put(CommonConsts.MAXFEE,"100000");//封顶手续费
			params.put(CommonConsts.FEETYPE,split[2]);// 费率类型
			params.put(CommonConsts.FEEVALUE,split[3]);// 费率值
			params.put(CommonConsts.OPERUSER,split[4]);//操作人
			
		}else if(ValueConsts.PRODUCTID_SETTLE_BAR_CODE.equals(productID)){
			String endDate = (Integer.parseInt(re.getReqDate().substring(0, 4))+50)+""+re.getReqDate().substring(4, re.getReqDate().length());
			url =UmfPropModel.INSTANCE.getPropValue(ConfigConsts.BORROW_RATE_URL);
			String rateDate =UmfPropModel.INSTANCE.getPropValue(ConfigConsts.BORROW_RATE_DATE);
			String[] split = rateDate.split(CommonConsts.AND);
			params.put(CommonConsts.MOPERATETYPE,split[0]);//操作类型
			params.put(CommonConsts.IS_ON,split[1]);//状态
			params.put(CommonConsts.MINVALUE,split[2]);//单笔保底
			params.put(CommonConsts.MAXVALUE,split[3]);//单笔封顶
			params.put(CommonConsts.DAY_LIMIT,split[4] );//日限额
			params.put(CommonConsts.PERCENT,split[5]);//可借款比例
			params.put(CommonConsts.TYPE,split[6]);//类型标识
			params.put(CommonConsts.FEETYPE,split[7]);//费率类型
			params.put(CommonConsts.FEERATE, split[8]);//费率
			params.put(CommonConsts.SETTYPE,split[9]);//佣金结算方式
			params.put(CommonConsts.FEEACCTYPE,split[10]);//扣费账户类型
			params.put(CommonConsts.ADVANCESTR,split[11]);//垫资方字符串
			params.put(XmlData.END_DATE, endDate);
		}
		
		try {
			logger.info("【配置费率】httpPostForm2Xml请求数据：params"+params+ "访问路径url="+ url);	
			Map<String, Object> rescon = HttpUtil.httpPostForm2Xml(url, params);
			logger.info("【配置费率】httpPostForm2Xml返回结果：",rescon);
			if(null==rescon||StringUtil.isEmpty((String) rescon.get(CommonConsts.RETCODE))){
				logger.info("【配置费率】失败,返回值rescon="+rescon);
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				return map;
			}
			if(RetCode.SUCCESS.equals(StringUtil.trim(rescon.get(CommonConsts.RETCODE)))){
				logger.info("【配置费率】成功！");			
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
			}else if(RetCode.ALLOCATION_EXIST.equals(StringUtil.trim(rescon.get(CommonConsts.RETCODE)))){
				logger.info("【配置费率】已存在，不需要配置！");		
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
			}else if(RetCode.BORROW_EXIST.equals(StringUtil.trim(rescon.get(CommonConsts.RETCODE)))){
				logger.info("【配置费率】已存在，不需要配置！");		
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
			}else{
				logger.info("【配置费率】失败,返回码"+rescon.get(CommonConsts.RETCODE));
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
			}
		}catch (Exception e) {
			logger.error("调用配置费率接口异常"+e);
			map.put(CommonConsts.RETCODE,RetCode.FAIL);
			return map;
		}
		return map;
	}
	
	
	/**
	 * 添加付款用途
	 * @param merId
	 * @return
	 */
	//@RequestMapping(value = "/configureBatchPay",produces="application/json;charset=UTF-8")
	//@ResponseBody
	public Map<String,String> configureBatchPay(String merId,String payeeName){
		Map<String,String> map = new HashMap<String, String>();
		// 组装请求参数
		BatchPayConf batchPayConf = new BatchPayConf();
		batchPayConf.setMerId(merId);
		batchPayConf.setCheckFlag(1);// 是否批量付款复核：0
		batchPayConf.setWhiteFlag(0);// 是否白名单校验：否0
		batchPayConf.setIsSendSms(0);// 是否下发短信：是1
		batchPayConf.setAccType(2);	//设置账户类型（过渡账户9,现金账户2）
		batchPayConf.setCreator(merId);// 填写商户号
		batchPayConf.setModUser(merId);// 填写商户号

		try {
			//先查表判断是否有商户配置
			BatchPayConf querybatchPayConf = new BatchPayConf();
			querybatchPayConf.setMerId(merId);
			logger.info("查询商户批量付款配置请求："+querybatchPayConf);
			BatchPayConf queryResBatchPayConf = batchPayConfRemote.getBatchPayConfDetail(querybatchPayConf);// 批量付款商户用途
			logger.info("查询商户批量付款配置响应："+queryResBatchPayConf);
			if(queryResBatchPayConf!=null){
				logger.error("保存【批量付款配置】:存在商户配置信息，不需要配置");
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
				return map;
			}		
			
		}catch (Exception e) {
			if(e.getMessage().indexOf("IndexOutOfBoundsException")==-1){
				//不存在IndexOutOfBoundsException
				logger.error("查询【批量付款配置】失败:" + e);
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				return map;
			}
			logger.info("查询【批量付款配置】成功，配置不存在，开始添加");
			// 接口调用
			try {
				logger.info("添加商户批量付款配置请求："+batchPayConf);
				batchPayConfRemote.addBatchPayConf(batchPayConf);// 添加到“批量付款商户配置表”
				//调用接口添加商户付款用途
				batchInsertBatchPayMU(merId,payeeName);
				logger.info("保存【批量付款配置】成功！");
				map.put(CommonConsts.RETCODE,RetCode.SUCCESS);
				return map;
			} catch (Exception e1) {
				logger.error("保存【批量付款配置】失败:" + e1);
				map.put(CommonConsts.RETCODE,RetCode.FAIL);
				return map;
			} 	
			
		}
		return map;
	}
	
	/**
	 * description : 批量添加商户付款用途关系
	 * @param merId
	 */
	public void batchInsertBatchPayMU(String merId,String payeeName) throws Exception {
		String usageIds = UmfPropModel.INSTANCE.getPropValue(ConfigConsts.USAGEIDS);
		String[] usageId = usageIds.split("&");
		for (int i = 0; i < usageId.length; i++) {
			BatchPayMU batchPayMU = new BatchPayMU();		//新建批量添加商户付款用途对象
			batchPayMU.setMerId(merId);						//添加商户号
			batchPayMU.setUsageId(usageId[i]);				//添加付款用途编号
			batchPayMU.setState(2);							//添加可用状态
			batchPayMU.setCreator(payeeName);				//添加创建人
			batchPayMU.setModUser(payeeName);				//添加修改人
			batchPayConfRemote.insertBatchPayMU(batchPayMU);//调用接口添加商户付款用途
		}
	}
}
